
let questions = [];
function fetchQuestions() {
    return new Promise((resolve, reject) => {
        const queryString = window.location.search;
        $.ajax({
            url: '/get_question' + queryString,
            method: 'GET',
            success: function(response) {
                if (response.code == 0) {
                    questions = response.data;  // 将数据赋值给全局变量
                    resolve(response.data);
                } else {
                    reject('获取题目失败');
                }
            },
            error: function(error) {
                reject(error);
            }
        });
    });
}
document.addEventListener('DOMContentLoaded', async function () {
    await fetchQuestions();

    let currentQuestionIndex = 0;
    const totalQuestions = questions.length;

    // 获取DOM元素
    const questionNumber = document.querySelector('.question-number');
    const questionText = document.querySelector('.question-text');
    const optionsContainer = document.querySelector('.options-container');
    const progressBar = document.querySelector('.progress');
    const progressText = document.querySelector('.progress-text');
    const prevButton = document.querySelector('.prev-btn');
    const nextButton = document.querySelector('.next-btn');

    // 更新进度条和文本
    function updateProgress() {
        const progress = ((currentQuestionIndex + 1) / totalQuestions) * 100;
        progressBar.style.width = `${progress}%`;
        progressText.textContent = `${progress.toFixed(0)}% (${currentQuestionIndex + 1}/${totalQuestions}题)`;
    }

    // 更新问题内容
    function updateQuestion() {
        const question = questions[currentQuestionIndex];
        questionNumber.textContent = `第 ${question.id + 1} 题`;
        questionText.textContent = question.text;

        // 清空并重新生成选项
        optionsContainer.innerHTML = '';
        question.options.forEach((option, index) => {
            const button = document.createElement('button');
            button.className = 'option-btn';
            button.innerHTML = `<span class="option-text" attr-id="">${String.fromCharCode(65 + index)}. ${option}</span>`;

            if (userAnswers[currentQuestionIndex] === index) {
                button.classList.add('selected');
            }

            button.addEventListener('click', () => selectOption(index));
            optionsContainer.appendChild(button);
        });

        // 更新按钮状态
        prevButton.disabled = currentQuestionIndex === 0;

        // 最后一题显示提交按钮
        if (currentQuestionIndex === totalQuestions - 1) {
            nextButton.innerHTML = '<i class="fas fa-check"></i> 提交测试';
            nextButton.classList.add('submit-btn');
        } else {
            nextButton.innerHTML = '下一题 <i class="fas fa-arrow-right"></i>';
            nextButton.classList.remove('submit-btn');
        }

        nextButton.disabled = !userAnswers[currentQuestionIndex];
        updateProgress();
    }

    // 选择选项
    let userAnswers = new Array(totalQuestions).fill(null);

    function selectOption(optionIndex) {
        // 移除所有选项的选中状态
        const options = optionsContainer.querySelectorAll('.option-btn');
        options.forEach(option => option.classList.remove('selected'));

        // 添加选中状态
        options[optionIndex].classList.add('selected');

        // 保存答案
        userAnswers[currentQuestionIndex] = optionIndex;

        // 启用下一题按钮
        nextButton.disabled = false;
    }

    // 上一题按钮点击事件
    prevButton.addEventListener('click', () => {
        if (currentQuestionIndex > 0) {
            currentQuestionIndex--;
            updateQuestion();
        }
    });

    // 下一题按钮点击事件
    nextButton.addEventListener('click', () => {
        if (currentQuestionIndex === totalQuestions - 1) {
            Swal.fire({
                text: '确定要提交测评吗？',
                icon: 'warning',
                showCancelButton: true,
                height: 322,
                width: 222,
                confirmButtonText: '提交',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.value) {
                   submitTest()
                } else {
                    // 用户点击了取消或关闭了弹窗
                    console.log('用户取消了操作，未提交');
                }
            });
        } else {
            currentQuestionIndex++;
            updateQuestion();
        }
    });

    // 添加提交测试函数
    function submitTest() {
        // 检查是否所有题目都已回答
        const unansweredQuestions = userAnswers.reduce((acc, curr, idx) => {
            if (curr === null) acc.push(idx + 1);
            return acc;
        }, []);

        if (unansweredQuestions.length > 0) {
            alert(`还有题目未完成：第 ${unansweredQuestions.join(', ')} 题`);
            return;
        }
        console.log(userAnswers)
        let key = window.location.search.split("=")
        $.ajax({
            url: '/report',
            method: 'POST',
            data:{
                option:userAnswers,
                key:key[1]
            },
            success: function(response) {
                if (response.code == 0) {
                    questions = response.data;  // 将数据赋值给全局变量
                    Swal.fire({
                        allowEscapeKey: false, // 禁止ESC键关闭弹窗
                        allowEnterKey: false, // 禁止回车键关闭弹窗
                        showCloseButton: false, // 隐藏关闭按钮
                        text: '提交成功,正在生成测评...',
                        icon: 'success',
                        timer: 2000, // 弹窗显示2秒
                        showConfirmButton: false, // 不显示确认按钮
                        allowOutsideClick: false, // 禁止点击弹窗外部关闭弹窗
                        didOpen: () => {
                            Swal.showLoading(); // 显示加载动画
                        },
                        willClose: () => {
                            return false; // 阻止弹窗关闭
                        }
                    }).then(() => {
                        // 2秒后进行页面跳转
                        window.location.href = '/results?order_no='+questions.order_no;
                    });
                } else {
                    Swal.fire({
                        text: response.msg,
                        timer: 1000,
                        icon: 'error',
                        // 指定自定义的 CSS 类名
                        customClass: {
                            popup: 'custom-swal'
                        },
                        height: 222,
                        width: 222
                    });
                }
            },
            error: function(error) {
                // reject(error);
            }
        });
        console.log('提交答案:', userAnswers);
        // location.href = 'report';
        // 可以跳转到结果页面或显示加载动画等
    }

    // 初始化显示第一题
    updateQuestion();
});

$(document).ready(function() {
    let clickTimes = []; // 记录点击时间的数组
    const MAX_CLICKS = 4; // 1秒内最大点击次数
    const TIME_WINDOW = 1000; // 1秒的时间窗口

    // 为选项按钮添加点击事件
    $('.options-container').on('click', '.option-btn', function(event) {
        const currentTime = new Date().getTime();

        // 清理超过1秒的点击记录
        clickTimes = clickTimes.filter(time => currentTime - time < TIME_WINDOW);

        // 检查1秒内的点击次数
        if (clickTimes.length >= MAX_CLICKS) {
            event.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: '答题过快',
                text: '请认真思考后再选择答案',
                timer: 2000,
                showConfirmButton: false
            });
            return;
        }

        // 记录这次点击的时间
        clickTimes.push(currentTime);

        // 原有的选项处理逻辑
        $('.option-btn').removeClass('selected');
        $(this).addClass('selected');

        // 延迟后自动进入下一题
        setTimeout(function() {
            $('.next-btn').click();
        }, 300);
    });
});
$(document).ready(function() {
    // 为选项按钮添加点击事件
    $('.options-container').on('click', '.option-btn', function() {
        // 移除所有选项的选中状态
        $('.option-btn').removeClass('selected');
        // 添加当前选项的选中状态
        $(this).addClass('selected');

        // 短暂延迟后自动进入下一题
        setTimeout(function() {
            // 触发下一题按钮的点击事件
            $('.next-btn').click();
        }, 300); // 300毫秒的延迟，让用户能看到选中效果
    });
});